# Maintainer: Miloš Komarčević <miloskomarcevic@aim.com>

_realname=lerc
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=3.0
pkgrel=3
pkgdesc="Limited Error Raster Compression library (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://github.com/Esri/lerc"
license=('Apache-2.0')
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-cc")
options=('strip' 'staticlibs')
source=("${_realname}-${pkgver}.tar.gz"::"${url}/archive/v${pkgver}.tar.gz"
        "Lerc.pc.in"
        "cmake_config_pc.patch"
        "0001-fix-static-library.patch")
sha256sums=('8c0148f5c22d823eff7b2c999b0781f8095e49a7d3195f13c68c5541dd5740a1'
            'b40845346ab11c8e2782fc49b8540782ab8040c16cc8e872d9531a42ecb3c8ff'
            '614c3893269eb0abdc45329cbd2830103365c676d70c9f34f3f0c5bc206de0a3'
            'f0a098f53a089188f4cf31a415e062fe17cdbddc972afd73dfe94da37e70856e')

prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}

  # https://github.com/Esri/lerc/pull/172
  cp "${srcdir}"/Lerc.pc.in "${srcdir}"/${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/cmake_config_pc.patch

  # https://github.com/Esri/lerc/pull/193
  patch -p1 -i "${srcdir}"/0001-fix-static-library.patch
}

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  [[ -d "${srcdir}/build-${MSYSTEM}-static" ]] && rm -rf "${srcdir}/build-${MSYSTEM}-static"
  mkdir -p "${srcdir}/build-${MSYSTEM}-static" && cd "${srcdir}/build-${MSYSTEM}-static"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=OFF \
      ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build ./

  [[ -d "${srcdir}/build-${MSYSTEM}-shared" ]] && rm -rf "${srcdir}/build-${MSYSTEM}-shared"
  mkdir -p "${srcdir}/build-${MSYSTEM}-shared" && cd "${srcdir}/build-${MSYSTEM}-shared"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build ./
}

package() {
  cd "${srcdir}/build-${MSYSTEM}-static"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install ./

  cd "${srcdir}/build-${MSYSTEM}-shared"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install ./

  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
